package com.html;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * *********************************************
 * @author Administrator
 * @FileName ParseImgs.java
 * @Description IMG标签转绝对路径
 **********************************************
 */
public class ParseImgs {
	public static final Logger LOG = LoggerFactory.getLogger(ParseImgs.class);

	public static String parse(String seed,String html){
		Document document = null;
		if(html != null && !"".equals(html)){
			URI base;
			try {
				base = new URI(seed);
				document = Jsoup.parse(html);
				Elements imgs = document.select("img");
				if(imgs != null && imgs.size() > 0){
					URI abs;
					String src;
					for(Element img : imgs){
						src = img.attr("src");
						if(src != null && !"".equals(src) && !src.startsWith("http") && !src.startsWith("https")){
							abs = base.resolve(src);
							img.attr("src", abs.toURL().toString());
						}
					}
					return document.body().html().toString();
				}else{
					return html;
				}
			} catch (URISyntaxException e) {
				LOG.info("seed-->" + seed + "-->html-->" + html);
				LOG.info("正文中的图片URL有问题,剔除");
			} catch (MalformedURLException e) {
				LOG.info("seed-->" + seed + "-->html-->" + html);
				LOG.info("正文中的图片URL有问题,剔除");
			}
		}
		return "";
	}

}
